package mongodao

import (
	mongomodel "mygame/app/model/mongoModel"
	mongopkg "mygame/pkg/mongoPkg"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type UserData struct{}

func (u UserData) db() *mongo.Collection {
	return mongopkg.DB.Collection(mongomodel.UserData{}.TableName())
}

func (u UserData) SaveData(uid int64, data map[string]interface{}) {
	filter := bson.M{"uid": uid}
	options := options.FindOneAndUpdate().SetUpsert(true) // 不存在时自动插入
	err := u.db().FindOneAndUpdate(mongopkg.Ctx, filter, bson.M{
		"$set": bson.M{"data": data},
	}, options)
	if err != nil {
		// utils.Println("SaveData error", err.Err().Error())
	}
}

func (u UserData) GetData(uid int64) map[string]interface{} {
	filter := bson.M{"uid": uid}
	userData := mongomodel.UserData{}
	u.db().FindOne(mongopkg.Ctx, filter).Decode(&userData)
	return userData.Data
}
